﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PSE.Framework.ProviderLoader.Configuration;
using PSE.Framework.ProviderLoader;
using System.Configuration;

namespace PSE.ProcessManager.ResourceAccess
{
    public class InstanceConfigurationResourceAccessFactory
    {
        private const string CONFIG_SECTION_NAME = "providerConfiguration";
        private const string PROVIDER_NAME = "instanceConfigurationResourceAccess";

        private static object _syncRoot = new object();
        private static IInstanceConfigurationResourceAccess _instance;
        public static IInstanceConfigurationResourceAccess CreateProvider()
        {
            try
            {
                lock (_syncRoot)
                {
                    if (_instance == null)
                    {
                        ProviderConfigurationSection configSection = System.Configuration.ConfigurationManager.GetSection(CONFIG_SECTION_NAME) as ProviderConfigurationSection;

                        if (configSection != null)
                        {
                            _instance = ProviderLoader<IInstanceConfigurationResourceAccess>.LoadProvider(configSection.Providers, PROVIDER_NAME);
                            return _instance;
                        }
                        else
                        {
                            throw new ArgumentNullException(PROVIDER_NAME);
                        }
                    }
                    else
                    {
                        return _instance;
                    }
                }
            }
            catch (Exception ex)
            {
                //System.Diagnostics.EventLog.WriteEntry("ResourceAccessFactory", ex.Message, System.Diagnostics.EventLogEntryType.Error);
                throw new ConfigurationErrorsException("Could not create an instance of Provider configured.", ex);
            }
        }
    }
}
